package net.luohuasheng.bee.proxy.mybatis.executor.processor;

import net.luohuasheng.bee.jdbc.tools.common.utils.CollectionUtils;
import net.luohuasheng.bee.proxy.core.utils.StringUtils;
import net.luohuasheng.bee.proxy.core.utils.jpa.dto.JpaColumnDto;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.List;
import java.util.stream.Collectors;

public class DeleteByIdProcessor extends BaseProcessor {

    public DeleteByIdProcessor(Configuration configuration, Class<?> entityClass) {
        super(configuration, entityClass);
    }


    @Override
    public SqlSource createSqlSource() {
        List<JpaColumnDto> columns = jpaTableDto.getColumns().stream().filter(jpaColumnDto -> jpaColumnDto.getTableLogic() != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(columns)) {
            return createSqlSource("delete from " + jpaTableDto.getName() + " where 1=1 " + createPkSql(jpaTableDto.getColumns()));
        } else {

            return createSqlSource("update  " + jpaTableDto.getName() + " set " + StringUtils.join(columns.stream().map(m -> {
                if (org.apache.commons.lang3.StringUtils.isNumeric(m.getTableLogic().delFlag())) {
                    return m.getName() + "=" + m.getTableLogic().delFlag() + "";
                } else {
                    return m.getName() + "='" + m.getTableLogic().delFlag() + "'";
                }
            }).collect(Collectors.toList()), ",") + addLogicConditions(columns) + createPkSql(jpaTableDto.getColumns()));
        }
    }


}
